// pages/userInfoCenter/index.js

const App = getApp();
const {Dialog, Toast} = require("../../../../config/modal")
const utils = require("../../../../utils/util")
const {LOCATION} = require("../../../../config/login.js")
import deviceUtil from "../../../../UI/lin-ui/dist/utils/device-util"

Page({
    /**
     * 页面的初始数据
     */
    data: {
        theamTextColor: App.globalData.theamTextColor,
        capsuleBarHeight: App.$getMenuButtonHeight(),
        file: {
            maxSize: 5242880,
            maxCount: 9,
            list: []
        },
        article: {
            id:'',
            getNewLocationontent: "",
            isAnon: false,
            type: "IMAGETEXT",
            isTop: false,
            images: '',
            city: '',
            newLocation: '',
        },
        showLoacation: false,
        locations: {
            prefix: '',
            regeocode: {},
            list: []
        },
        formItem: {},
        rules:
            {
                name: {
                    msg: "请填写收货人",
                    required: true,
                },
                phone: {val: "", msg: "请填写联系电话", required: true},
                province: {val: "", msg: "请选择地区", required: true},
                address: {val: "", msg: "请填写详细地址", required: true},
            },
    },
    URL: {
        save: "/article/publishArticle",
    },
    page: {
        article: '/pages/tabbar/dynamic/list/index'
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.hideShareMenu();
        if (!utils.isInvalid(options.item)) {
            let item = JSON.parse(options.item);
            let province = item.province;
            let cityName = item.city;
            let area = item.district;
            this.setData({
                'address.item': item,
                'address.area': province + ' ' + cityName + ' ' + area,
            })
        }
        utils.saveUrlParams(this, options, ['item'])
    },
    onShow() {
       
    },


    onIsAnonChange({detail}) {
        this.setData({
            'article.isAnon': detail
        })
    },
    onContentChange(e){
        this.setData({
            'article.content': e.detail.value
        })
    },

    // 获取当前所在位置
    getNewLocation() {
        if (LOCATION.isAllowedLocation()) {
            wx.showLoading({
                title: '位置解析中',
                mask: true,
            })
            LOCATION.getDetailLocation(res => {
                wx.hideLoading()
                let province = res.regeocode.addressComponent.province
                let city = res.regeocode.addressComponent.city
                let district = res.regeocode.addressComponent.district
                let prefix = province + city + district
                this.setData({
                    'locations.formatted_address': res.regeocode.formatted_address.replace(prefix, ""),
                    'locations.province': province,
                    'locations.city': city,
                    'locations.district': district,
                    'locations.prefix': prefix,
                    'locations.list': res.regeocode.pois,
                })
                this.setData({
                    'showLoacation': true
                })
            })
            return
        }
        LOCATION.allowed(res=>{
            // 授权地理位置
            if(res){
                this.getNewLocation();
            }
        })
    },

    // 选择地址
    selectAddress(e) {
        this.setData({
            'article.newLocation': e.currentTarget.dataset.item
        })
        this.closeLocation();
    },
    // 清楚地址
    clearAddress() {
        this.setData({
            'article.newLocation': ''
        })
    },

    // 关闭弹框
    closeLocation() {
        this.setData({
            'showLoacation': false,
        })
    },

    // 提交地址信息
    submitInfo() {

        // 处理图片 转base64

        let imgs = this.data.file.list
        let imgBase64 = "";
        imgs.forEach(file => {
            imgBase64 += utils.fileToBase64Sync(file.url) + "&&";
        })
        // console.log(imgBase64);
        this.setData({
            'article.images': imgBase64
        })

        if (utils.isInvalid(imgBase64) && utils.isInvalid(this.data.article.content)) {
            Toast('需要输入内容/图片哦 😊～')
        }
        this.setData({
            'article.city': LOCATION.getCity()
        })
        if (utils.isInvalid(this.data.article.id)) {
            this.save();
            return;
        }
        this.update();
    },

    save() {
        App.$post(true, this.URL.save, this.data.article, res => {
            this.reqResult(res);
        })
    }
    ,
    update() {
        App.$post(true, this.URL.update, this.data.address.item, res => {
            this.reqResult(res);
        })
    }
    ,
    reqResult(res) {
        if (res.R) {
            Dialog.alert({
                message: res.msg,
                width: "250px",
                confirmButtonColor: "#D2691E",
                confirmButtonText: "确定",
            }).then(() => {
               // this.goBack();
               App.$redirectTo(this.page.article,false);
            })
        }
    }
    ,

    // 文件读取前
    fileBefore(event) {
        event.detail.callback(true)
    }

    ,fileOversize(event) {
        Dialog.alert({
            message: '图片每张只允许5M以内的照片',
            width: "250px",
            confirmButtonColor: "#D2691E",
            confirmButtonText: "关闭",
        }).then(() => {
        });
    },

    fileDelete(event) {
        let index = event.detail.index;
        let files = this.data.file.list;
        files.splice(index, 1);
        this.setData({
            "file.list": files,
        })
    }

    // 证件选择
    ,afterRead(event) {
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        const files = event.detail.file;
        let sourceFiles = this.data.file.list;
        files.forEach(file=>{
            sourceFiles.push({url: file.url, name: ""})
        })
        this.setData({
            "file.list": sourceFiles
        })
    }

    ,goBack() {
        wx.navigateBack();
    }

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    ,onReady: function () {

    }
    ,


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    }
    ,

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
    }
    ,

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    }
    ,

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
